package org.zjx.data;

import lombok.Getter;
import org.zjx.command.entity.screen.Npc;
import org.zjx.command.entity.screen.Room;
import org.zjx.command.entity.screen.Scene;
import org.zjx.command.entity.screen.Teleport;
import org.zjx.data.screen.*;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;

@Getter
public class FileBasedWorldManager {
    private final Map<String, Scene> scenes = new HashMap<>();
    private final Map<String, Npc> globalNpcCache = new HashMap<>();
    private final Map<String, Room> globalRoomCache = new HashMap<>();
    private final List<Teleport> globalTeleportCache = new ArrayList<>();
    private final String scenesDirectory;

    public FileBasedWorldManager(String scenesDirectory) {
        this.scenesDirectory = scenesDirectory;
    }

    // 方式1：从Java构建器加载场景
    public void loadFromBuilders() {
        // 加载所有场景构建器
        loadScene(new ChangAnSceneBuilder().build());
        loadScene(new JianYeSceneBuilder().build());
        loadScene(new JiangNanYeWaiSceneBuilder().build());
        loadScene(new DongHaiWanSceneBuilder().build());
        loadScene(new ChangShouCunSceneBuilder().build());
        loadScene(new AoLaiGuoSceneBuilder().build());
        loadScene(new DaTangGuoJingSceneBuilder().build());
        loadScene(new DaTangJingWaiSceneBuilder().build());
        loadScene(new DiFuSceneBuilder().build());
        loadScene(new DaTangGuanFuSceneBuilder().build());
        loadScene(new HuaShengSiSceneBuilder().build());
        loadScene(new WuZhuangGuanSceneBuilder().build());
        loadScene(new HuaGuoShanSceneBuilder().build());
        loadScene(new QiLinShanSceneBuilder().build());
        loadScene(new HuanJingHuaGuoShanSceneBuilder().build());

        // 可以继续添加其他场景构建器...
        System.out.println("从Java构建器加载了 " + scenes.size() + " 个场景");
    }

    // 方式2：从JSON文件加载场景
    public void loadFromJsonFiles() {
        File dir = new File(scenesDirectory);
        if (!dir.exists()) {
            System.out.println("场景目录不存在: " + scenesDirectory);
            return;
        }

        File[] jsonFiles = dir.listFiles((d, name) -> name.endsWith(".json"));
        if (jsonFiles != null) {
            for (File file : jsonFiles) {
                try {
                    String json = new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8);
                    Scene scene = SceneJsonSerializer.jsonToScene(json);
                    loadScene(scene);
                    System.out.println("从JSON加载场景: " + scene.name);
                } catch (Exception e) {
                    System.err.println("加载场景文件失败: " + file.getName());
                    e.printStackTrace();
                }
            }
        }

        System.out.println("从JSON文件加载了 " + scenes.size() + " 个场景");
    }

    // 方式3：自动模式（优先JSON，不存在则用Java构建器）
    public void autoLoad() {
        File dir = new File(scenesDirectory);
        if (dir.exists()) {
            // 优先使用JSON文件
            loadFromJsonFiles();
        } else {
            // 回退到Java构建器
            loadFromBuilders();
            // 并生成JSON文件供下次使用
            generateJsonFiles();
        }
    }

    // 生成所有场景的JSON文件
    public void generateJsonFiles() {
        File dir = new File(scenesDirectory);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        for (Scene scene : scenes.values()) {
            try {
                String fileName = scene.name + ".json";
                String filePath = new File(dir, fileName).getAbsolutePath();
                String json = SceneJsonSerializer.sceneToJson(scene);
                Files.write(Paths.get(filePath), json.getBytes(StandardCharsets.UTF_8));
                System.out.println("生成JSON文件: " + fileName);
            } catch (Exception e) {
                System.err.println("生成JSON文件失败: " + scene.name);
                e.printStackTrace();
            }
        }
    }

    private void loadScene(Scene scene) {
        scenes.put(scene.name, scene);
        buildNpcCache(scene);
        buildRoomCache(scene);
        buildTeleportCache(scene);
    }

    private void buildRoomCache(Scene scene) {
        for (Room room : scene.rooms) {
            globalRoomCache.put(room.name, room);
        }
    }

    private void buildTeleportCache(Scene scene) {
        globalTeleportCache.addAll(scene.teleports);
    }

    private void buildNpcCache(Scene scene) {
        for (Npc npc : scene.npcs) {
            globalNpcCache.put(scene.name + ":" + npc.name, npc);
        }
        for (Room room : scene.rooms) {
            for (Npc npc : room.npcs) {
                globalNpcCache.put(scene.name + ":" + room.name + ":" + npc.name, npc);
            }
        }
    }

    // 其他方法保持不变...
    public Scene getScene(String sceneName) { return scenes.get(sceneName); }

    public Npc findNpc(String sceneName, String npcName) {
        String key = sceneName + ":" + npcName;
        Npc npc = globalNpcCache.get(key);
        if (npc != null) return npc;

        Scene scene = getScene(sceneName);
        if (scene != null) {
            for (Room room : scene.rooms) {
                key = sceneName + ":" + room.name + ":" + npcName;
                npc = globalNpcCache.get(key);
                if (npc != null) return npc;
            }
        }
        return null;
    }

    public Npc findNpc(String npcName) {
       List<Npc> npcs = new ArrayList<>(getGlobalNpcCache().values());
        return npcs.stream().filter(npc -> npc.name.equals(npcName)).findFirst().orElse(null);
    }
}